﻿namespace BEGDC.CC.Web.EZVisit.Controls
{
    #region Using Directives

    using System;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using ASBCC.Workflow.K2Manager;
    using BL.Common;
    using Utility.Castle;
    using Utility.Extensions;

    #endregion

    public partial class EZVRequestQuotAttch : EZVRequestBaseControl
    {
        protected override void PreRenderPartialView()
        {
            this.SetVisibility();
            this.SetViewData();
        }

        protected override void SetViewData()
        {
            if (this.EZVisitApplication == null)
            {
                return;
            }

            this.BindAttachments();
            this.BindQuotation();

            string provider = this.EZVisitApplication.ProviderKey;

            if (ValueIncludes(this.EZVisitApplication.PDC, this.CurrentUser))
            {
                string type = this.EZVisitApplication.QuotationType;

                if (type.IsNotNullOrWhiteSpace() && type.Equals("PDCQuotation"))
                {
                    this.dgQuotation.Columns[7].Visible = true;

                    if (!this.Editable)
                    {
                        this.secComment.Visible = true;
                        this.vw_Comment.Text = this.EZVisitApplication.QuotationComments;
                    }
                }

                if (this.EZVisitApplication.CODPPManagerDate != null && !this.Editable)
                {
                    this.secProvider.Visible = true;
                    this.vw_Providers.Text = provider.IsNotNullOrWhiteSpace() && provider.VariantEquals("Others") ? this.EZVisitApplication.OthersProviderDesc : this.EZVisitApplication.ProviderDesc;
                }
            }
            else if (ValueIncludes(this.EZVisitApplication.CODPPManager, this.CurrentUser))
            {
                this.secComment.Visible = true;
                this.secProvider.Visible = true;
                this.edt_UploadSection.Visible = false;
                this.pnlAttch.Visible = false;
                this.edt_Header.Visible = false;
                this.lblMessage.Visible = true;

                if (this.Editable)
                {
                    this.BindProviders();

                    if (provider.IsNotNullOrWhiteSpace())
                    {
                        this.edt_Providers.SelectedValue = provider;
                        this.secOtherProvider.Visible = provider.VariantEquals("Others");
                        this.edt_OtherProvider.Text = this.EZVisitApplication.OthersProviderDesc;
                    }

                    this.edt_Comment.Text = this.EZVisitApplication.QuotationComments;
                }
                else
                {
                    this.vw_Comment.Text = this.EZVisitApplication.QuotationComments;
                    this.vw_Providers.Text = provider.IsNotNullOrWhiteSpace() && provider.VariantEquals("Others") ?  this.EZVisitApplication.OthersProviderDesc : this.EZVisitApplication.ProviderDesc;
                }

                this.dgQuotation.Columns[7].Visible = true;
            }

            if (this.EZVisitApplication.QuotationType.IsNotNullOrWhiteSpace())
            {
                this.lblMessage.Visible = false;
            }
        }

        protected override bool Validate(out string error)
        {
            error = string.Empty;

            // Action raised by PDC
            if (this.CurrentActionType.Equals(K2ActionType.Upload))
            {
                if (this.edt_Upload1.Visible)
                {
                    error = @"- [Quotation Attch.] Quotation attachment was not provided.\n";
                    return false;
                }
            }

            // Action raised by COD-PP Manager
            if (this.CurrentActionType.Equals(K2ActionType.Validate))
            {
                if (this.dgQuotation.Items.Count != 2)
                {
                    error = @"- [Quotation Attch.] Quotation was not provided by the PDC.\n ";
                    return false;
                }

                bool valid = (from DataGridItem i in this.dgQuotation.Items select (RadioButton)i.Cells[7].FindControl("rbSelect")).Any(rb => rb.Checked);

                if (!valid)
                {
                    error = @"- [Quotation Attch.] Quotation was not selected.\n";
                    return false;
                }

                if (this.edt_Providers.SelectedItem == null) 
                {
                    error = @"- [Quotation Attch.] The provider for this delegation was not selected.\n";
                    return false;
                }
            }

            return true;
        }

        public override void Save(EZVisitApplicationTableEntity app)
        {
            if (this.EZVisitApplication == null)
            {
                return ;
            }

            switch (this.CurrentActionType)
            {
                case K2ActionType.Validate:
                case K2ActionType.ReplyAskForMore:
                    if (ValueIncludes(this.EZVisitApplication.CODPPManager, this.CurrentUser))
                    {
                        foreach (DataGridItem i in from DataGridItem i in this.dgQuotation.Items let rb = (RadioButton)i.Cells[7].FindControl("rbSelect") where !rb.Checked select i)
                        {
                            app.QuotationType = i.Cells[8].Text;
                            app.QuotationComments = this.edt_Comment.Text;
                            break;
                        }

                        string provider = this.edt_Providers.SelectedValue;

                        app.ProviderKey = provider;
                        app.ProviderDesc = null;
                        app.OthersProviderDesc = null;

                        if (provider.VariantEquals("Others"))
                        {
                            app.OthersProviderDesc = this.edt_OtherProvider.Text;
                        }
                        else
                        {
                            app.ProviderDesc = this.edt_Providers.SelectedItem.Text;
                        }
                    }

                    break;

                case K2ActionType.Withdraw:
                    app.QuotationType = app.QuotationComments = app.ProviderKey = app.ProviderDesc= app.OthersProviderDesc = null;

                    this.ClearPDCQuotation();
                    break;
            }

           base.Save(app);
        }

        public void BindQuotation()
        {
            if (this.EZVisitApplication == null || this.EZVisitApplication.AppIDIsNull() || !this.Visible)
            {
                return;
            }

            string[] range = null;

            if (ValueIncludes(this.EZVisitApplication.PDC, this.CurrentUser))
            {
                string type = this.EZVisitApplication.QuotationType;

                range = type.IsNotNullOrWhiteSpace() && type.Equals("PDCQuotation") && !this.Editable ? new[] { "'PDCQuotation'", "'TAQuotation'" } : new[] { "'PDCQuotation'" };
            }
            else if (ValueIncludes(this.EZVisitApplication.CODPPManager, this.CurrentUser))
            {
                range = new[] { "'PDCQuotation'", "'TAQuotation'" };
            }

            var dt = this.GetAttachments(range).OfType<UploadFileTableEntity>().ToDataTable();

            this.dgQuotation.DataSource = dt;
            this.dgQuotation.DataBind();

            this.edt_Upload1.Visible = this.Editable & dt.Rows.Count == 0;
        }

        private void ClearPDCQuotation()
        {
            var attachments = this.GetAttachments(new[] { "'PDCQuotation'" });

            foreach (UploadFileTableEntity attachment in attachments)
            {
                attachment.IsEnabled = false;

                UploadFileManager.Update(attachment);
            }
        }

        protected void dgQuotation_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                return;
            }

            var cell = e.Item.Cells[7];

            var rbSelect = (RadioButton)cell.FindControl("rbSelect");
            var btnDelete = (ImageButton)cell.FindControl("btnDelete");

            string type = this.EZVisitApplication.QuotationType;

            if (ValueIncludes(this.EZVisitApplication.PDC, this.CurrentUser))
            {
                if (this.Editable)
                {
                    rbSelect.Visible = false;
                    btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
                }
                else
                {
                    btnDelete.Visible = false;

                    rbSelect.Enabled = false;

                    if (type.IsNotNullOrWhiteSpace())
                    {
                        rbSelect.Checked = type.Equals("PDCQuotation") ? e.Item.Cells[8].Text.Equals("TAQuotation") : e.Item.Cells[8].Text.Equals("PDCQuotation");
                    }
                }
            }
            else if (ValueIncludes(this.EZVisitApplication.CODPPManager, this.CurrentUser))
            {
                btnDelete.Visible = false;
                rbSelect.GroupName = "SelectQuotation";
                rbSelect.Enabled = this.Editable;

                if (type.IsNotNullOrWhiteSpace())
                {
                    rbSelect.Checked = e.Item.Cells[8].Text.Equals(type.Equals("PDCQuotation") ? "TAQuotation" : "PDCQuotation");
                }
            }
        }

        protected void dgQuotation_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            DeleteAttachement(Convert.ToInt32(e.Item.Cells[0].Text));

            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "reloadpdcquotation", "reload('pdcquotation');", true);
        }

        private UploadFileTableEntitySet GetAttachments(string[] attchTypes)
        {
            string rangeCondition = string.Join(",", attchTypes);

            string condition = string.Format("AppID={0} and IsEnabled=1 and AttachmentTypeKey in ({1})", this.EZVisitApplication.AppID, rangeCondition);

            return UploadFileManager.SelectByCondition(condition);
        }

        private void BindAttachments()
        {
            if (this.EZVisitApplication == null || this.EZVisitApplication.AppIDIsNull())
            {
                return;
            }

            var dt = this.GetAttachments(new[] { "'AGENDA'", "'BUDGET'", "'TAQuotation'" }).OfType<UploadFileTableEntity>().ToDataTable();

            this.dgAttachment.DataSource = dt;
            this.dgAttachment.DataBind();
        }

        private static void DeleteAttachement(int fileId)
        {
            var attachment = UploadFileManager.SelectByKeys(fileId);

            if (attachment == null)
            {
                return;
            }

            attachment.IsEnabled = false;
            UploadFileManager.Update(attachment);
        }

        private static bool ValueIncludes(string src, string dest)
        {
            src = ";" + src + ";";
            dest = ";" + dest + ";";
            return src.IndexOf(dest, StringComparison.InvariantCultureIgnoreCase) != -1;
        }

        private void BindProviders()
        {
            var utility = (IUtility)AppContainer.Instance[ServiceConst.UtilityService];
            var list = utility.BuildDicList("Provider");

            this.edt_Providers.DataSource = list;
            this.edt_Providers.DataValueField = "DicItemKey";
            this.edt_Providers.DataTextField = "Description";
            this.edt_Providers.DataBind();

            this.edt_Providers.Items.Add(new ListItem("Others  其他", "Others"));
        }

        protected void edt_Providers_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.secOtherProvider.Visible = this.edt_Providers.SelectedValue.VariantEquals("Others");
        }
    }
}